﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ResourceManagement.Client;
using Microsoft.ResourceManagement.Client.WsTrust;
using System.Threading;

namespace SampleQAGateQuestionAsker {
    public class QAGateQuestionAsker {
        private Dictionary<int, String> passwordResetAnswers;

        public void addAnswer(KeyValuePair<int, String> newAnswer) {
            passwordResetAnswers.Add(newAnswer.Key, newAnswer.Value);
        }

        public QAGateQuestionAsker() {
            this.passwordResetAnswers = new Dictionary<int, string>();
        }


        protected virtual void OnAskPasswordResetQuestion(AskPasswordResetQuestionArgs e) {
            if (AskPasswordResetQuestion != null) {
                //Invokes the delegates.
                AskPasswordResetQuestion(this, e);
            }
        }
        public event AskPasswordResetQuestionHandler AskPasswordResetQuestion;

        public Dictionary<int, String> AskQuestions(WorkflowAuthenticationChallenge authenticationChallenge) {
            //reset any past answers
            passwordResetAnswers.Clear();
            int questionsAsked = 0;

            do {
                //If the number of answers = the number of questions asked
                //We need to ask another question
                if (passwordResetAnswers.Count == questionsAsked) {
                    int questionNumber;
                    string questionString;

                    questionNumber = PickRandomQuestion(authenticationChallenge.GateQuestions.Length);
                    questionString = authenticationChallenge.GateQuestions[questionNumber - 1];

                    KeyValuePair<int, String> question = new KeyValuePair<int, string>(questionNumber, questionString);
                    AskPasswordResetQuestionArgs e = new AskPasswordResetQuestionArgs();
                    e.question = question;
                    OnAskPasswordResetQuestion(e);
                    questionsAsked++;
                }
            } while (passwordResetAnswers.Count < authenticationChallenge.QuestionsPresentedToUser);

            return passwordResetAnswers;

        }

        private int PickRandomQuestion(int numberOfQuestions) {
            bool found = false;
            int pick;
            do {
                Random randNum = new Random();
                pick = randNum.Next(1, numberOfQuestions + 1);
                if (!passwordResetAnswers.ContainsKey(pick)) {
                    found = true;
                }
            } while (!found);

            return pick;

        }
    }
}
